package com.itheima.es.mq;

import com.alibaba.fastjson.JSON;
import com.hmall.common.es.ItemDoc;
import com.hmall.common.pojo.Item;
import com.hmall.feignclient.ItemFeignClient;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 苏成博
 * @date 2023-03-20 10:52
 */
@Component
public class ItemSearchMqConsumer {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemFeignClient itemFeignClient;
    @RabbitListener(queues = "item.queue")
    public void updateEsItem(Item item) {
        try {
            if (item != null) {
                Integer status = item.getStatus();
                if (status == 1) {
                    Item itemById = itemFeignClient.findItemById(item.getId());
                    //商品上架
                    ItemDoc itemDoc = new ItemDoc(itemById);
                    //创建request请求
                    IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
                    //对象转换为json
                    String jsonString = JSON.toJSONString(itemDoc);
                    //添加DSL语句
                    request.source(jsonString, XContentType.JSON);
                    client.index(request, RequestOptions.DEFAULT);
                }
                if (status == 2) {
                    //商品下架
                    DeleteRequest deleteRequest = new DeleteRequest("item", item.getId().toString());
                    client.delete(deleteRequest, RequestOptions.DEFAULT);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
